<?php

/***
 * @author songqiaoli
 * 发送广泛模板短信
 *例如:【好汉科技】{$msg}
 */

namespace App\Models;

use GuzzleHttp\Client;

class SmsExtensiveTemplate
{
    /**
     * 获取通知类账号
     */
    private function getAmountNotice()
    {
        $config = config('smsextensive')['sms_extensive_notice'];
        unset($config['appcode']);
        return $config;

    }

    /**
     * 获取营销类类账号
     */
    private function getAmountMarketing()
    {
        $config = config('smsextensive')['sms_extensive_marketing'];
        unset($config['appcode']);
        return $config;

    }

    /**
     * 获取appkey
     * @param type: 1(通知) 2(营销)
     */
    private function getAppKey($type = 1)
    {
        return $type == '1' ? config('smsextensive')['sms_extensive_notice']['appkey'] : config('smsextensive')['sms_extensive_marketing']['appkey'];
    }

    /**
     * 获取appsecret
     * @param type: notice(通知) marketing(营销)
     */
    private function getAppSecret($type = 1)
    {
        return $type == '1' ? config('smsextensive')['sms_extensive_notice']['appsecret'] : config('smsextensive')['sms_extensive_marketing']['appsecret'];
    }

    /**
     * 获取appcode
     *
     */
    private function getAppCode()
    {
        return 1000;
    }

    /**
     * 获取签名
     *
     */
    private function getAutograph()
    {
        return config('smsextensive')['autograph'];
    }


    /**
     * 批量发送短息 ，发送内容相同的短息
     * @param $type 1.消息通知2.营销类
     * @param array $phone 手机号用户
     *
     * @param $msg        短信内容
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     * eg:
     *      $model = new  SmsExtensiveTemplate();
     * $phone =  15110167623,18701605391 ;
     * $model->sendBatch($phone, '喜喜');//内容相同
     */
    public function sendBatch($phone = '', $msg = '', $type = 1)
    {
        //判断余额够不够发短信的
        $balance = $this->getBalance($type);

        if (array_key_exists('code', $balance)) {
            return '获取余额接口报错' . json_encode($balance);
        }
        $phoneLength = count(explode(',', $phone));
        if ($balance['balance'] < $phoneLength) {
            return '短信余额不足:剩余' . $balance['balance'];
        }
        if (empty($phone)) {
            return '请传输逗号拼接格式的手机号';
        }
        if (empty($msg)) {
            return '请传输短信内容';
        }

        $headers = array(
            'Content-type' => 'application/json',
            'Accept-Charset' => 'utf-8'
        );
        $data = ['appkey' => $this->getAppKey($type), 'appcode' => $this->getAppCode(), 'sign' =>
            $this->getSign($type), 'phone' => $phone, 'msg' => $this->getAutograph() . $msg, 'timestamp' => $this->getMillisecond()
        ];


        $url = config('smsextensive')['url_batch'];
        //请求设置
        $config = array(
            //请求链接
            'base_uri' => $url,
            //请求头
            'headers' => $headers,
            'body' => json_encode($data),
            //显示具体错误
            'http_errors' => false,
            'verify' => false,
            'timeout' => 60
        );

        $client = new Client($config);
        $request = $client->request(strtoupper('POST')); // 请求
        $http_status = $request->getStatusCode(); // 响应状态码
        $response = $request->getBody()->getContents(); //响应内容
        return json_decode($response, true);
    }

    /**获取签名
     * @return string
     * $type 1.通知 2.营销
     */
    private function getSign($type = 1)
    {
        return md5($this->getAppKey($type) . $this->getAppSecret($type) . $this->getMillisecond());
    }

    /**
     * 获取发送短信结构体
     * @param $phone 手机号
     * @param $msg 消息
     *
     */
    private function getSmsStruct($phone, $msg)
    {
        return [
            'phone' => ''
        ];
    }

    /**
     * 获取当前系统时间(精确到毫秒)
     * @return float
     */
    function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }

    /**一对一发送，群发
     * @param $content =[['msg'=>'','phone'=>'','extend'=>''],['msg'=>'【好汉科技】','phone'=>'','extend'=>'']]
     * @param  $type = 1.通知 2.营销类
     * @throws \GuzzleHttp\Exception\GuzzleException
     * eg:
     * $model = new  SmsExtensiveTemplate();
     * $content = [['phone' => '18701605391', 'msg' => '【好汉科技】六时吉祥', 'extend' => '']];
     * var_dump($model->sendDistinct($content));;//内容相同
     */
    public function sendDistinct($content = [], $type = 1)
    {
        //判断余额够不够发短信的
        $balance = $this->getBalance($type);
        if (array_key_exists('code', $balance)) {
            return '获取余额接口报错' . json_encode($balance);
        }
        if ($balance['balance'] < count($content)) {
            return '短信余额不足:剩余' . $balance['balance'];
        }
        if (empty($content)) {
            return '请传输数组格式的发送内容';
        }
        $headers = array(
            'Content-type' => 'application/json',
            'Accept-Charset' => 'utf-8'
        );
        $data = ['appkey' => $this->getAppKey($type), 'appcode' => $this->getAppCode(), 'sign' =>
            $this->getSign($type), 'sms' => $content, 'timestamp' => $this->getMillisecond()
        ];
        $url = config('smsextensive')['url_distinct'];
        //请求设置
        $config = array(
            //请求链接
            'base_uri' => $url,
            //请求头
            'headers' => $headers,
            'body' => json_encode($data),
            //显示具体错误
            'http_errors' => false,
            'verify' => false,
            'timeout' => 60
        );

        $client = new Client($config);
        $request = $client->request(strtoupper('POST')); // 请求
        $http_status = $request->getStatusCode(); // 响应状态码
        $response = $request->getBody()->getContents(); //响应内容
        return json_decode($response, true);

    }

    /***
     * 查询余额
     * 查询账号余额，单位为条
     * @param $type 1.短信通知 2.营销类
     */
    public function getBalance($type = 1)
    {
        $headers = array(
            'Content-type' => 'application/json',
            'Accept-Charset' => 'utf-8'
        );
        $data = ['appkey' => $this->getAppKey($type), 'appcode' => $this->getAppCode(), 'sign' =>
            $this->getSign($type), 'timestamp' => $this->getMillisecond()
        ];
        $url = config('smsextensive')['url_balance'];
        //请求设置
        $config = array(
            //请求链接
            'base_uri' => $url,
            //请求头
            'headers' => $headers,
            'body' => json_encode($data),
            //显示具体错误
            'http_errors' => false,
            'verify' => false,
            'timeout' => 60
        );

        $client = new Client($config);
        $request = $client->request(strtoupper('POST')); // 请求
        $http_status = $request->getStatusCode(); // 响应状态码
        $response = json_decode($request->getBody()->getContents(), true); //响应内容
        return $response;

    }

}